package com.cxs.security;

import com.cxs.common.exception.MyLoginException;
import com.cxs.entity.User;
import com.cxs.service.IPermissionService;
import com.cxs.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    IUserService userService;

    @Autowired
    IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过username从数据库中读取用户
        User user = userService.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码不正确!");
        }
        // 参数：用户id，用户名，密码，权限信息（角色、菜单权限）
        return new AccountUser(user.getId(), username, user.getPassword(), getUserAuthority(user.getId()));
    }

    /**
     * 根据用户Id获取权限（角色、菜单权限）
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId) {
        // 获取权限信息（角色、菜单权限组成的字符串）
        String authority = permissionService.getAuthorityByUserId(userId);
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
        if (grantedAuthorities.size() == 0) {
            throw new MyLoginException("A0205");
        }
        return grantedAuthorities;
    }
}
